// pages/phone/phone.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    checked: '',
    phoneNumber: '',
    codeMsg: '获取验证码',
    code: '',
    iscountingDown: false,
    disabled: "disabled"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  checkLegal(e) {
    var val = e.detail.value,
      reg = /^1[34578]\d{9}$/,
      _this = this,
      data = {},
      isLegal = reg.test(val);
    if (isLegal && !_this.data.isCountingDown) {
      data['checked'] = 'checked';
      data['phoneNumber'] = val;
    }else {      
      data['checked'] = '';
      data['phoneNumber'] = val;
    }
    _this.setData(data);

    //检查是否可以提交表单
    if (isLegal && _this.data.code.length == 6) _this.setData({ disabled: ''});
      else _this.setData({ disabled: 'disabled' });
    
  },
  getCode() {
    var _this = this,
        checked = _this.data.checked,
        reg = /^1[34578]\d{9}$/,
        time = 59,
        f = null
    if(checked == 'checked' && !_this.data.isCountingDown) {

      //TODO 发起网络请求，请求验证码

      wx.showToast({
        title: '验证码已发送',
        duration: 2000
      });

      f = setInterval(function() {
        _this.setData({
          codeMsg: time + 's后重发',
          checked: '',
          isCountingDown: true
        });
        if(time < 0) {
          var data = {};
          clearInterval(f);
          data['codeMsg'] = '重新发送';
          data['isCountingDown'] = false;

          if(reg.test(_this.data.phoneNumber)) {
            data['checked'] = 'checked';
          }
          _this.setData(data);
        }
        time--;
      }, 1000);
    }
  },
  checkCode(e) {
    //验证所有输入框是否都已输入且合法
    var code = e.detail.value,
        _this = this,
        phone = _this.data.phoneNumber,
        reg = /^1[34578]\d{9}$/
    _this.setData({code: code});
    if(code.length == 6 && reg.test(phone)) _this.setData({disabled: ''});
      else _this.setData({ disabled: 'disabled' });
  },
  submit(e) {
    var val = e.detail.value;

    //TODO 发送绑定请求并返回信息
    wx.showModal({
      title: '提示',
      content: '绑定成功！',
      showCancel: false,
      success: function() {
        wx.reLaunch({
          url: '/pages/map/map',
        })
      }
    })
  }
})